package com.atguigu.spzx.common.service.interceptro;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.spzx.common.util.AuthContextUtil;
import com.atguigu.spzx.model.entity.h5.UserInfo;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName: UserLoginAuthInterceptor
 * @Package: com.atguigu.spzx.common.service.interceptro
 * @Description 拦截器, 负责将userInfo对象放入ThreadLoad中
 * @Author 孤妤
 * @Date: 2023/12/19 18:31
 */
@Component
public class UserLoginAuthInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取token,不为空根据token拿redis中的userInfo对象
        String token = request.getHeader("token");
        if (StringUtils.hasLength(token)){
            String userInfoStr = redisTemplate.opsForValue().get("user:login:" + token);
            if (StringUtils.hasLength(userInfoStr)){
                UserInfo userInfo = JSONObject.parseObject(userInfoStr, UserInfo.class);
                // 将对象放入threadLoad线程中
                AuthContextUtil.setUserInfo(userInfo);
            }
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AuthContextUtil.removeUserInfo();
    }
}
